<template>
  <div>
    <pro-table
      ref="tableRef"
      :data="tableData"
      row-key="id"
      :columns="columns"
      :total="total"
      :tool-button="false"
      @search="commEvent.onSearch"
      :page-change="commEvent.onPageChange"
    >
      <!-- 顶部操作 -->
      <template #tableHeader>
        <el-row justify="end">
          <el-button type="danger" plain :disabled="tableIds.length <= 0" @click="commEvent.onBatchDelete"> 批量删除 </el-button>
        </el-row>
      </template>
      <!-- 操作 -->
      <template #operation="scope">
        <el-button type="danger" link @click="commEvent.onDelete(scope.row)">删除</el-button>
      </template>
    </pro-table>
    <!-- 插样详情 -->
    <sample-detail v-model="detailVisible" :data="currentRowData" />
  </div>
</template>

<script setup lang="ts">
import { ref, h, onMounted } from "vue"
import ProTable from "@/components/ProTable/index.vue"
import SampleDetail from "./components/SampleDetail.vue"
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface"
import { computed } from "vue"
import { ElButton, ElMessage, ElMessageBox } from "element-plus"

// 参数
const tableRef = ref<ProTableInstance>() // 表格实例
const tableData = ref<any[]>([]) // 表格数据
const total = ref<number>(0) // 数据总数
const detailVisible = ref<boolean>(false) // 详情
const currentRowData = ref<any>(null) // 当前选中行数据
const tableIds = computed(() => tableRef.value?.selectedListIds || []) // 选中数据ID
// 页码参数
const pageParams = ref({
  pageIndex: 1,
  pageSize: 10
})
// 表单配置
const columns: ColumnProps<any>[] = [
  { type: "selection" },
  {
    prop: "sort",
    label: "序号",
    width: 80,
    render: scope => h("span", scope.$index + 1 + (pageParams.value.pageIndex - 1) * pageParams.value.pageSize)
  },
  { prop: "creator", label: "创建人", width: 180, search: { el: "select" } },
  {
    prop: "sampleDetail",
    label: "插样详情",
    width: 180,
    render: scope => {
      // 当状态为"进行中"时显示蓝色的"详情"链接
      if (scope.row.status === "进行中") {
        return h(
          ElButton,
          {
            type: "primary",
            link: true,
            onClick: () => {
              currentRowData.value = scope.row
              detailVisible.value = true
            }
          },
          () => "详情"
        )
      }
      return h("span", "-")
    }
  },
  { prop: "createTime", label: "创建时间", width: 180, search: { el: "date-picker" } },
  { prop: "startTime", label: "实验开始时间", width: 220 },
  { prop: "endTime", label: "实验结束时间", width: 220 },
  { prop: "status", label: "状态" },
  { prop: "operation", label: "操作", width: 120, fixed: "right" }
]
// 方法
const commEvent = {
  // 获取表格数据
  getTableData: async (params: any) => {
    // const { data } = await asyncFun(params)
    // 模拟数据，包含状态为"进行中"的记录
    tableData.value = [
      {
        id: "001",
        creator: "张三",
        status: "进行中",
        createTime: "2024-01-15 10:30:00",
        startTime: "2024-01-15 11:00:00",
        endTime: "-",
        samples: [
          {
            holeNumber: 1,
            sampleName: "名称1",
            qualitativeQuantitative: "定性",
            group: "用户组",
            detectionNumber: "1200"
          },
          {
            holeNumber: 2,
            sampleName: "名称2",
            qualitativeQuantitative: "定量",
            group: "管理组",
            detectionNumber: "1201"
          }
        ]
      },
      {
        id: "002",
        creator: "李四",
        status: "已完成",
        createTime: "2024-01-14 09:20:00",
        startTime: "2024-01-14 09:30:00",
        endTime: "2024-01-14 15:30:00",
        samples: []
      },
      {
        id: "003",
        creator: "王五",
        status: "已完成",
        createTime: "2024-01-13 14:15:00",
        startTime: "2024-01-13 14:30:00",
        endTime: "2024-01-13 18:45:00",
        samples: []
      },
      {
        id: "004",
        creator: "赵六",
        status: "已取消",
        createTime: "2024-01-12 08:00:00",
        startTime: "-",
        endTime: "-",
        samples: []
      }
    ]
    total.value = 4
  },
  // 查询
  onSearch: () => {
    tableRef.value?.search()
    pageParams.value.pageIndex = 1
    const _search = tableRef.value?.searchParam
    commEvent.getTableData({ ...pageParams.value, ..._search })
  },
  // 分页
  onPageChange: (page: number, size: number) => {
    pageParams.value.pageIndex = page
    pageParams.value.pageSize = size
    const _search = tableRef.value?.searchParam
    commEvent.getTableData({ ...pageParams.value, ..._search })
  },
  // 单个删除
  onDelete: async (row: any) => {
    // 检查是否为"进行中"状态
    if (row.status === "进行中") {
      ElMessage.warning("进行中的实验无法删除")
      return
    }

    try {
      await ElMessageBox.confirm("确定要删除该记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })

      // TODO: 调用后端接口删除数据
      // await deleteRecord(row.id)

      // 从表格数据中移除
      const index = tableData.value.findIndex(item => item.id === row.id)
      if (index > -1) {
        tableData.value.splice(index, 1)
        total.value--
      }

      ElMessage.success("删除成功")
    } catch (error) {
      // 用户点击了取消
      console.log("取消删除")
    }
  },
  // 批量删除
  onBatchDelete: async () => {
    const selectedIds = tableIds.value
    if (selectedIds.length === 0) {
      ElMessage.warning("请选择要删除的记录")
      return
    }

    // 获取选中的行数据
    const selectedRows = tableData.value.filter(item => selectedIds.includes(item.id))

    // 检查是否包含"进行中"状态的实验
    const hasInProgressExperiment = selectedRows.some(row => row.status === "进行中")

    if (hasInProgressExperiment) {
      ElMessage.warning("选中的记录中包含进行中的实验，无法删除")
      return
    }

    try {
      await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.length} 条记录吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })

      // TODO: 调用后端接口批量删除数据
      // await batchDeleteRecords(selectedIds)

      // 从表格数据中移除选中的记录
      tableData.value = tableData.value.filter(item => !selectedIds.includes(item.id))
      total.value = tableData.value.length

      // 清空选中状态
      tableRef.value?.clearSelection()

      ElMessage.success(`成功删除 ${selectedIds.length} 条记录`)
    } catch (error) {
      // 用户点击了取消
      console.log("取消批量删除")
    }
  }
}
onMounted(() => {
  commEvent.getTableData(pageParams.value)
})
</script>
